package com.rt.easyjava.base.biz1.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rt.easyjava.base.biz1.bean.TmptAuthUserBiz;
import com.rt.easyjava.base.biz1.controller.base.TmptAuthUserController;
import com.rt.easyjava.base.biz1.dto.TmptAuthUserBizDto;
import com.rt.easyjava.common.base.MyQueryWrapper;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.base.UserDetailsDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 前端控制器
 * 1，自定义代码：源码生成器，创建模板，第一次生成源码时，会自动创建此类，之后生成源码时，此类将不做修改处理；
 *    所以，程序员应该在这个类里写自己的代码，后续需求变更，自动生成源码时，不影响此类。
 * 2，用户信息可直接形参获取：String (_userId，_loginName，_userName，_companyId，_userJson)
 * @author wuxiaoyong
 * @since 2020-06-13
 * 用户信息可直接形参获取：String (_userId，_loginName，_userName，_companyId，_userJson)
 */
@Slf4j
@Api(tags = "TmptAuthUserBizController -  控制类")
@RequestMapping("/coding/tmptAuthUser")
@Controller
public class TmptAuthUserBizController extends TmptAuthUserController {

    //@PreAuthorize("hasAuthority('tmptAuthUser:query')")
    @ApiOperation("通过登录名查询登录次数")
    @GetMapping(value = "/selectLoginTimesByLoginName")
    @ResponseBody
    public Result selectLoginTimesByLoginName(String loginName){
        Integer loginTimes = super.tmptAuthUserBizService.selectByKey("loginname", loginName).getLogintimes();
        return Result.builder().setObj(loginTimes).success();
    }


    @PostMapping(value = "/validatePassword")
    @ResponseBody
    public Result validatePassword(@RequestBody Map map){
        try {
            System.out.println("------->");
            // System.out.println(map);
            String loginname = (String) map.get("loginname");
            String passwordInput = (String) map.get("passwordInput");
            String passwordUser = (String) map.get("passwordUser");
            String loginTimes = (String) map.get("loginTimes");
            tmptAuthUserBizService.validatePassword(loginname, passwordInput, passwordUser, loginTimes);
        }catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
            return Result.builder().fault(e.getLocalizedMessage());
        }
        return Result.builder();
    }


    // 查询我的下属列表
    @PreAuthorize("hasAuthority('tmptAuthUser:query')")
    @ApiOperation(" 查询我的下属列表")
    @GetMapping(value = "/selectMySubordinates")
    @ResponseBody
    public Result selectMySubordinates(String _userId){
        return tmptAuthUserBizService.selectSubordinatesByUserId(Long.parseLong(_userId));
    }



    @PreAuthorize("hasAuthority('tmptAuthUser:query')")
    @ApiOperation("分页查询列表（适合单表查询）")
    @GetMapping(value = "/page")
    @ResponseBody
    public Result page(@ModelAttribute TmptAuthUserBizDto tmptAuthUserBizDto){
        return super.page(tmptAuthUserBizDto, null);
    }


    @PreAuthorize("hasAuthority('tmptAuthUser:query')")
    @ApiOperation("以ID作为父节点，查询子树")
    @GetMapping(value = "/tree")
    @ResponseBody
    @Override
    public Result tree (Long id) {
        return super.tree(id);
    }

    @PreAuthorize("hasAuthority('tmptAuthUser:query')")
    @ApiOperation("自定义sql分页查询（mapper.xml, 适合多表查询）")
    @GetMapping(value = "/myPage")
    @ResponseBody
    public Result myPage(@ModelAttribute TmptAuthUserBizDto tmptAuthUserBizDto, String userDetailsJson){
        UserDetailsDto userDetailsDto = UserDetailsDto.getUserDetailsDto(userDetailsJson, "tmptAuthUser:query");

        Page<TmptAuthUserBiz> page = new Page<>(tmptAuthUserBizDto.getPage(), tmptAuthUserBizDto.getLimit());

        // 查询条件
        TmptAuthUserBiz tmptAuthUserBizQuery = mapper.map(tmptAuthUserBizDto, TmptAuthUserBiz.class);
        // set deleteflag default 0, 查询参数时，默认只查有效数据
        tmptAuthUserBizQuery.setDeleteflagDefaultZero();
        // 数据访问边界 0：全部数据， 10：机构内部数据
        rebuildDataLimitQueryBean(tmptAuthUserBizQuery, userDetailsDto);

        // 多表查询时，plus自带不支持，这里封装一个工具类处理，mapper.xml中主表别名是t1, 给所有非空字段加别名； 特殊查询条件，在工具类中要忽略掉，最后自定义增加。
        QueryWrapper<TmptAuthUserBiz> queryWrapper = MyQueryWrapper.buildQueryWrapper(tmptAuthUserBizQuery , "createdate", "name", "loginname");
        //特殊查询条件
        queryWrapper.ge(tmptAuthUserBizDto.getCreatedate_Start()!=null,"t1.createdate",tmptAuthUserBizDto.getCreatedate_Start());
        queryWrapper.le(tmptAuthUserBizDto.getCreatedate_End()!=null,"t1.createdate",tmptAuthUserBizDto.getCreatedate_End());
        queryWrapper.like(tmptAuthUserBizDto.getName()!=null,"t1.name",tmptAuthUserBizDto.getName());
        queryWrapper.like(tmptAuthUserBizDto.getLoginname()!=null,"t1.loginname",tmptAuthUserBizDto.getLoginname());
        queryWrapper.orderBy(tmptAuthUserBizDto.getCondition(), tmptAuthUserBizDto.isAsc(), "t1."+tmptAuthUserBizDto.getColumn());

        return tmptAuthUserBizService.myPage(page, queryWrapper);
    }

    // 数据访问边界 0：全部数据， 10：机构内部数据
    public void rebuildDataLimitQueryBean(TmptAuthUserBiz tmptAuthUserBizQuery, UserDetailsDto userDetailsDto){
        if (userDetailsDto==null) return;
        int dataLimitType = userDetailsDto.getDataLimitType();
        if (dataLimitType == 10) {
            tmptAuthUserBizQuery.setTmptAuthDeptId(Integer.parseInt(userDetailsDto.getCompanyId()));
        }
        if (dataLimitType == 20) {
            tmptAuthUserBizQuery.setCreatemanId(Long.parseLong(userDetailsDto.getUserId()));
        }
    }

    @PreAuthorize("hasAuthority('tmptAuthUser:query')")
    @ApiOperation("查询所有")
    @GetMapping(value = "/selectBy")
    @ResponseBody
    public Result selectBy(@ModelAttribute TmptAuthUserBizDto tmptAuthUserBizDto){
        return super.selectBy(tmptAuthUserBizDto, null);
    }


    @PreAuthorize("hasAuthority('tmptAuthUser:query')")
    @ApiOperation("selectById")
    @GetMapping(value = "/selectById")
    @ResponseBody
    @Override
    public Result selectById(Long id){
        return super.selectById(id);
    }


    @PreAuthorize("hasAuthority('tmptAuthUser:query')")
    @ApiOperation("SQL动态多选项, spring动态调用")
    @GetMapping(value = "/select4column")
    @ResponseBody
    @Override
    public Result select4column(String columnName){
        return super.select4column(columnName);
    }

    @PreAuthorize("hasAuthority('tmptAuthUser:create')")
    @ApiOperation("新增对象")
    @PostMapping(value = "/create")
    @ResponseBody
    @Override
    public Result create(@RequestBody TmptAuthUserBizDto tmptAuthUserBizDto,
                    String _userId, String _userName, String _companyId){
        return super.create(tmptAuthUserBizDto, _userId, _userName, _companyId);
    }


    @PreAuthorize("hasAuthority('tmptAuthUser:update')")
    @ApiOperation("编辑对象")
    @PostMapping(value = "/update")
    @ResponseBody
    @Override
    public Result update(@RequestBody TmptAuthUserBizDto tmptAuthUserBizDto,
                        String _userId, String _userName){
        return super.update(tmptAuthUserBizDto, _userId, _userName);
    }


    @PreAuthorize("hasAuthority('tmptAuthUser:delete')")
    @ApiOperation("逻辑删除对象，由deleteflag控制：0:有效，1:已删除。")
    @PostMapping(value = "/delete")
    @ResponseBody
    @Override
    public Result delete(Long id, String _userId, String _userName){
        return super.delete(id, _userId, _userName);
    }


    @PreAuthorize("hasAuthority('tmptAuthUser:deletePhysical')")
    @ApiOperation("物理删除对象，默认注释了核心调用方法，请按需启用")
    @PostMapping(value = "/deletePhysical")
    @ResponseBody
    @Override
    public Result deletePhysical(Long id){
        return super.deletePhysical(id);
    }

}
